package com.wmh.baseservice.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.admin.pojo.AdMenu;
import com.wmh.baseservice.admin.pojo.AdRoleMenu;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.mybatisplus.structure.CustomQueryWrapper;
import com.wmh.baseservice.common.redis.utils.RedisUtil;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantMenu;
import com.wmh.baseservice.merchant.pojo.MerchantRoleMenu;
import com.wmh.baseservice.merchant.mapper.MerchantRoleMenuMapper;
import com.wmh.baseservice.merchant.service.MerchantRoleMenuService;
import com.wmh.baseservice.common.mybatisplus.methods.CommonServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wmh generator
 * @since 2022-01-09
 */
@Service
public class MerchantRoleMenuServiceImpl extends CommonServiceImpl<MerchantRoleMenuMapper, MerchantRoleMenu> implements MerchantRoleMenuService {

    @Resource
    private MerchantRoleMenuMapper merchantRoleMenuMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public List<MerchantMenu> selectRoleMenu(MerchantRoleMenu merchantRoleMenu) {
        return merchantRoleMenuMapper.selectRoleMenu(merchantRoleMenu);
    }

    @Transactional
    @Override
    public String setRoleMenu(Long roleId, Long[] menuIds) {
        // 查询该角色拥有权限的菜单
        QueryWrapper<MerchantRoleMenu> queryWrapper = new CustomQueryWrapper<>();
        queryWrapper.eq(MerchantRoleMenu.ROLE_ID, roleId);
        List<MerchantRoleMenu> list = super.list(queryWrapper);
        if (list.size() > 0){
            // 删除该角色原有的菜单权限
            if (!super.remove(queryWrapper)) {
                throw new ServiceException("删除菜单权限失败");
            }
        }
        list = new ArrayList<>();
        MerchantRoleMenu merchantRoleMenu;
        // 新增菜单权限
        for (Long menuId : menuIds) {
            merchantRoleMenu = new MerchantRoleMenu();
            merchantRoleMenu.setRoleId(roleId);
            merchantRoleMenu.setMenuId(menuId);
            list.add(merchantRoleMenu);
        }
        // 插入菜单权限
        if (!super.saveBatch(list)) {
            throw new ServiceException("新增菜单权限失败");
        }
        // 刷新权限
        redisUtil.hdel("roleMenu", roleId.toString());
        return ReturnBody.success();
    }
}
